<template>
  <div>
     <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="visible" width="700px" height="700px" style="overflow:auto">
        <el-steps :active="active" align-center class="margin-bottom20">
        <el-step title="选择课程" />
        <el-step title="订单" />
      </el-steps>
      <el-form :model="form" ref="form" label-width="100px" v-if="active==0">
            <div v-for="(item,index) in form.goods" :key="index" class="good-item">
               <el-row>
                  <el-col :span="20">
                      <el-form-item label="商品名称：" prop="goodname"  :prop="'goods.'+index+'.goodname'" 
                                :rules="[
                                { required: true, message: '请选择商品名称', trigger: 'change' }
                                ] ">
                          <el-select v-model="item.goodname" filterable remote reserve-keyword placeholder="请输入商品名称" :remote-method="remoteGoodsMethod" :loading="goodloading" clearable @change="changeGood($event,index)">
                            <el-option
                              v-for="item in goodList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                            </el-option>
                        </el-select>
                          <!-- <nice-select v-model="item.goodname" placeholder="请选择商品名称" clearable :options="goodList" @change="changeGood($event,index)"></nice-select> -->
                      </el-form-item>
                  </el-col>
                  <el-col :span="2" class="margin-top10 margin-left10">
                      <i class="el-icon-delete" @click="deleteGood(item,index)" v-if="index !== 0"></i>
                  </el-col>
               </el-row>    
                <div v-for="(course,indx) in item.courseList" :key="indx">
                  <el-row>
                    <el-col :span="20">
                      <el-form-item label="课程名称：">
                          <span>{{course.label}}</span>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="20">
                        <el-form-item label="选择期次：" :prop="'goods.'+index+'.courseList.'+indx+'.period'" :rules="{required: true, message: '请选择期次', trigger: 'change'}" >
                            <nice-select v-model="course.period" placeholder="请选择期次" clearable :options="course.periodList"></nice-select>
                        </el-form-item>
                    </el-col> 
                  </el-row>
                </div>
                <div class="line" v-if="index!==form.goods[form.goods.length-1]"></div>
             </div>
            <el-row>
              <el-col class="center"><el-button type="text" icon="el-icon-circle-plus" size="small" @click="addGood()">添加商品</el-button></el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                  <el-form-item label="选择优惠：" prop="favorable">
                      <nice-select v-model=" form.favorable" placeholder="请选择优惠" clearable :options="favorableList"></nice-select>
                  </el-form-item>
              </el-col>
            </el-row>
            <div class="right">
              <span class="margin-right20">共{{form.goods.length}}件商品</span><span>合计：¥{{ form.favorable ? 0 :totalPrice}}</span>
            </div>
      </el-form>
      <div v-if="active===1">
          <ul v-for="(item,index) in  form.goods" :key="index">
               <li class="m-good-title"><span>{{item.goodname | filterGoodName(goodList) }}</span><span>¥{{item.goodname.split('-')[1]}}</span></li>
               <ul>
                 <li v-for="(course,$index) in item.courseList" :key="$index">
                   <p>{{course.label}}</parse>
                   <p>{{course.period | filterPeriod(course.periodList)}}</p>
                 </li>
               </ul>
               <p class="right">×1</p>
          </ul>
          <div class="right m-order-time">
             <p>下单时间：{{createTime}}</p>
             <p v-if="form.favorable">优惠信息：s端优惠</p>
             <p>
               <span class="margin-right20">共{{form.goods.length}}件商品</span>
               <span>合计：¥{{form.favorable ? 0 :totalPrice}}</span>
              </p>
          </div>
          <el-form :model="pay" ref="wayForm" label-width="100px" :rules="wayRules">
            <el-row :gutter="20">
             <el-col :span="10">
                <el-form-item label="支付方式：" prop="way">
                    <nice-select v-model="pay.way" placeholder="请选择支付方式" clearable :options="payWayList"></nice-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                 <el-form-item label="支付金额：" v-if="form.favorable||(!totalPrice)">
                    <span>0</span>
                </el-form-item>
                <el-form-item label="支付金额：" prop="amount" v-else>
                    <el-input v-model="pay.amount" placeholder="请输入支付金额" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false" size="small">取消</el-button>
          <el-button @click="goBack" size="small" v-if="active===1">返回上一步</el-button>
          <el-button type="primary" @click="dataFormSubmit"  size="small">确定</el-button>
      </span>
  </el-dialog>
  </div>
</template>
<script>
import {cascadeQuery} from '@/api/api.js'
import {batchNotify, getGoodsList, getPeriodListByCourseId, buyCourse} from '@/api/user.js'
let goodname = '', period = ''
export default {
  data () {
    return {
      visible: false,
      goodloading: false,
      copyGoodsList: [],
      applyBack: [],
      applyBackSuccess: [],
      applyBackError: [],
      title: '',
      active: 0,
      indx: 0,
      goodList: [],
      applyList: [],
      createTime: '',
      pay: {way: '', amount: ''},
      form: {
        goods: [
          {goodname: '', courseList: []}
        ],
        favorable: ''
      },
      wayRules: {
        way: [
             { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入支付金额', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!(/^(0|([1-9]\d*))(\.\d{1,2})?$/.test(value))) {
              callback('请输入正数且可输入两位小数')//eslint-disable-line
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      totalPrice: 0,
      payWayList: [
        {label: '支付宝', value: 0},
        {label: '微信', value: 1},
        {label: '银行转账', value: 3}
      ],
      student_id: '',
      courseList: [],
      favorableList: [
        {label: 'S端免费', value: '1'}
      ]
    }
  },
  props: {
    applyWay: {
      type: String,
      default: ''
    },
    multipleSelection: {
      type: Array,
      default: []
    }
  },
  filters: {
    filterGoodName (val, goodList) {
      goodList.forEach(ele => {
        if (ele.value === val) {
          goodname = ele.label.split(' ')[0]
        }
      })
      return goodname
    },
    filterPeriod (val, data) {
      data.forEach(ele => {
        if (ele.value === val) {
          period = ele.label
        }
      })
      return period
    }
  },
  methods: {
    init (id) {
      this.visible = true
      this.totalPrice = 0
      this.student_id = id || 0
      this.active = 0
      this.copyGoodsList = []
      this.title = this.applyWay === 'batch' ? '批量报名' : '报名'
      this.$nextTick(() => {
        this.form = {
          goods: [
          {goodname: '', courseList: []}
          ],
          favorable: ''
        }
        this.pay = {way: '', amount: ''}
        this.$refs['form'].resetFields()
      })
    },
    async remoteGoodsMethod (query) {
      if (query !== '') {
        this.goodloading = true
        let res = await getGoodsList(
          {
            'table_name': 'nice_goods_virtual',
            'goods_name': query
          }
      )
        if (res[0]) { return }
        this.goodloading = false
        if (res[1] && res[1].code === 0) {
          if (res[1].data && res[1]) {
            this.goodList = res[1].data.map(ele => {
              ele.goods_name = ele.goods_name + ' ' + ele.course_count + '讲' + ' ' + ele.retail_price + '元'
              return {
                label: ele.goods_name,
                value: ele.id + '-' + ele.retail_price,
                price: ele.retail_price
              }
            })
            this.copyGoodsList.push(...this.goodList)
          }
        } else {
          this.$message.error(res[1].msg)
        }
      }
    },
    async changeGood (e, index) {
      this.totalPrice = 0
      this.form.goods.forEach(ele => {
        this.totalPrice = this.totalPrice + (+ele.goodname.split('-')[1])
      })
      if (+e.split('-')[0]) {
        let res = await cascadeQuery(
          {
            'table_name': 'nice_goods_course',
            'condition': {
              'goods_id': +e.split('-')[0]
            },
            'member': 'course_name,course_lesson_name,lesson_num'
          }
      )
        if (res[0]) { return }
        if (res[1] && res[1].code === 0) {
          this.courseList = []
          if (res[1].data && res[1].data.length) {
            res[1].data.forEach((item, indx) => {
              this.courseList.push({
                value: item.course_id,
                label: item.course_name + ' ' + item.lesson_num + '讲',
                period: '',
                periodList: []
              })
              this.getPeriod(e, item, index, indx)
            })
            this.$set(this.form.goods, index, {goodname: e, courseList: this.courseList})
          }
        } else {
          this.$message.error(res[1].msg)
        }
      }
      this.goodList = []
    },
    async getPeriod (e, item, index, indx) {
      let res = await getPeriodListByCourseId(
        {
          'table_name': 'nice_course_period',
          'course_id': item.course_id
        }
      )
      if (res[0]) { return }
      if (res[1] && res[1].code === 0) {
        if (res[1].data && res[1].data.length) {
          this.courseList[indx].periodList = res[1].data.map(ele => {
            ele.start_date = ele.start_date ? ele.start_date.substring(0, 10) : ''
            ele.end_date = ele.end_date ? ele.end_date.substring(0, 10) : ''
            let date = ele.start_date ? ele.start_date + '~' + ele.end_date : ''
            let frequency = ele.frequency ? JSON.parse(ele.frequency) : []
            let week = '周' + this.$filterFrequency(frequency)
            ele.label = '第' + ele.sort + '期' + ' ' + date + ' ' + week
            return {
              label: ele.label,
              value: ele.id
            }
          })
        }
      } else {
        this.$message.error(res[1].msg)
      }
    },
    addGood () {
      this.form.goods.push({goodname: '', courseList: []})
    },
    deleteGood (item, index) {
      this.form.goods.splice(index, 1)
      this.totalPrice = 0
      this.form.goods.forEach(ele => {
        this.totalPrice = this.totalPrice + (+ele.goodname.split('-')[1])
      })
    },
    goBack () {
      this.active = this.active - 1
    },
    // 表单提交
    dataFormSubmit () {
      if (this.active === 0) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let date = new Date()
            this.createTime = this.$formatDate(date, 'yyyy-MM-dd hh:mm')
            this.active = this.active + 1
          }
        })
      } else {
        this.$refs['wayForm'].validate((valid) => {
          if (valid) {
            if (this.pay.amount > this.totalPrice) {
              this.$message({
                message: '支付金额不能大于总金额！',
                type: 'warning'
              })
              return false
            }
            this.submit()
          }
        })
      }
    },
    async submit () {
      let orderGoods = []
      this.applyBackSuccess = []
      this.applyBackError = []
      this.applyList = []
      this.indx = 0
      this.form.goods.forEach(ele => {
        if (ele.courseList && ele.courseList.length) {
          ele.courseList.forEach(course => {
            orderGoods.push({
              'course_id': course.value,
              'course_period_id': course.period,
              'goods_id': +ele.goodname.split('-')[0],
              'goods_type': '0',
              'goods_name': this.copyGoodsList.find(good => { return good.value.split('-')[0] === ele.goodname.split('-')[0] }).label.split(' ')[0],
              'course_name': course.label.split(' ')[0]
            })
          })
        }
      })
      let res = this.applyWay === 'batch' ? await buyCourse([
        { 'table_name': 'nice_order',
          'list': this.multipleSelection.map(ele => {
            return {
              'user_id': ele.user_id,
              'order_amount': this.totalPrice,
              'pay_amount': this.form.favorable ? 0 : +this.pay.amount,
              'pay_type': this.pay.way,
              'is_use_coupon': +this.form.favorable,
              'pay_info': [{
                'pay_way': this.pay.way,
                'user_id': ele.user_id
                // 'pay_number': this.form.favorable ? 0 : +this.pay.amount
              }],
              'order_goods_period': orderGoods
            }
          }
        )}
      ]) : await buyCourse([
        {
          'table_name': 'nice_order',
          'list': [
            {
              'user_id': this.student_id,
              'order_amount': this.totalPrice,
              'pay_amount': +this.pay.amount,
              'pay_type': this.pay.way,
              'is_use_coupon': +this.form.favorable,
              'pay_info': [{
                'pay_way': this.pay.way,
                'user_id': this.student_id
                // 'pay_number': +this.pay.amount
              }],
              'order_goods_period': orderGoods
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        let arr = []
        if (data.data[0].list && data.data[0].list.length) {
          data.data[0].list.forEach(ele => {
            arr.push(ele.order_number)
          })
        }
        if (this.applyWay === 'batch') {
          this.applyList = arr
          this.handleBack(arr)
        } else {
          this.batchNotify(arr[0])
        }
      } else {
        this.$message.error(data.msg)
      }
    },
    async handleBack (list) {
      let promises = list.map(ele => { return this.batchNotify(ele) })
    },
    async batchNotify (e) {
      let res = await batchNotify({'orderNum': e})
      if (this.applyWay === 'batch') {
        this.indx = this.indx + 1
        if (res[1] && res[1].code === 0) {
          this.applyBackSuccess.push(res[1])
        } else {
          this.applyBackError.push(res[1])
        }
        if (this.indx === this.applyList.length) {
          let len1 = this.applyBackSuccess.length || 0
          let len2 = this.applyBackError.length || 0
          this.visible = false
          this.$message.success(`共${len1}名学生报名成功，${len2}名学生报名失败！`)
          this.$emit('refreshDataList')
        }
        return res
      }
      if (res[0]) { return }
      if (res[1] && res[1].code === 0) {
        this.visible = false
        this.$message.success('报名成功！')
        this.$emit('refreshDataList')
      } else {
        this.$message.error(res[1].msg)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-scroll{.el-dialog__body{height: 500px;overflow: scroll}}
.m-good-title{
  display: flex;
  justify-content: space-between;
}
.good-item{
  margin-bottom: 20px;
  .line{width:540px;height: 1px;background: #dcdfe6;margin-left: 10px;}
}
ul{
  list-style: none;
  p{margin: 0px;padding: 0px;}
}
.m-order-time{
  border-bottom: 1px solid #ccc;
  margin-bottom: 30px;
}
</style>